<template>
  <div>
    <h1 class="text-center">通讯录</h1>
    <!-- 列表 -->
    <v-list :list="list" @dele="delItem" @edit="edit"></v-list>
    <div class="text-center"><button class="btn btn-primary btn-lg" @click="isShow=isAdd=true">添加联系人</button></div>
    <!-- 弹框 -->
    <v-dialog ref="dia" v-if="isShow" @add="addItem" @editItem="editItem" @cel="cancel" :isAdd="isAdd"></v-dialog>
  </div>
</template>

<script>
import vList from "./List.vue"
import vDialog from "./Dialog.vue"
export default {
    components:{
        vList,
        vDialog,
    },
    data(){
        return {
            list:[
                {id:1,name:"田成平",tel:"13112345678"},
                {id:2,name:"王恒",tel:"13156781234"},
                {id:3,name:"张浩天",tel:"15112345678"}
            ],
            isShow:false, //是否显示
            isAdd:true, //是否是添加
        }
    },
    methods:{
        //添加了添加按钮，添加一条数据
        addItem(user){
            this.isShow = false;
            this.list.push({
                ...user,
                id:this.list.length+1
            })
        },
        //取消
        cancel(){
            this.isShow = false;
        },
        //删除一条记录
        delItem(index){
            this.list.splice(index,1);
        },
        //点击编辑框，显示弹框
        edit(index){
            this.isShow=true;
            this.isAdd = false;

            //父组件--调用lookup(子组件) -- 子组件如果是通过v-if，子组件没有渲染
            this.$nextTick(()=>{
              //    console.log(this.$refs.dia);
              //    console.log(this.list[index]); //要操作的数据
              //    
               this.$refs.dia.lookup(this.list[index],index); //
            }) 
        },
        //编辑一条数据
        editItem(obj){
           this.isShow = false;
           //不在data中定义的属性，改变不会页面的重新渲染，数组的方法都会让页面进行重新渲染
           this.list.splice(obj.index,1,obj);
        }
    }
}
</script>

<style>

</style>